package com.gps.pe.utility;

import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * Utility class to load SQL file based on database
 * 
 * @author Gps
 *
 */
public final class GetSQLQuery {
	private static final Logger LOGGER = Logger.getLogger(GetSQLQuery.class);
	private static Properties properties = null;
	private static String dbType;
	private static String DB_FILE_REFERENCE = "/com\\gps\\pe\\dao\\gps_pe_db_";

	/**
	 * Method read a specific query from property file based on key
	 * 
	 * @param key
	 * @return
	 */
	public static String getQuery(final String key) {
		String query = null;
		if (properties == null) {
			if (StringUtils.isStringEmpty(dbType)) {
				dbType = "mysql";
			}
			readSQLQueries();
		}
		query = properties.getProperty(key);

		LOGGER.info("Key [" + key + "] & Query [" + query + "]");
		return query;
	}

	public static void setDbType(String dbType) {
		GetSQLQuery.dbType = dbType;
	}

	/**
	 * Method read SQL Query from a db file based on database
	 * 
	 * @param dbName
	 */
	private static void readSQLQueries() {
		if (properties == null) {
			LOGGER.info("Loading DB file...");
			DB_FILE_REFERENCE = DB_FILE_REFERENCE + dbType + ".properties";
			LOGGER.info("DB file is [" + DB_FILE_REFERENCE + "]...");
			try {
				properties = PropertyReaderUtil.readProperties(DB_FILE_REFERENCE);
			} catch (IOException e) {
				LOGGER.error("DB file [" + DB_FILE_REFERENCE + "] not found..." + e);
			}
		}
	}

	private GetSQLQuery() {
		// Utility class, hide constructor.
	}
}
